package com.le.tester.webpage.queue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 描述：延迟队列测试
 */
public class DelayedQueueTester {
    private static final Logger LOG= LoggerFactory.getLogger(DelayedQueueTester.class);
    public static void main(String[] args) throws InterruptedException {
        test();
    }

    private static void test() throws InterruptedException {
        DelayQueue<Delayed> delayedQueue = new DelayQueue<>();
        producer(delayedQueue);
        LOG.info("start task task from queue ");
        while (!delayedQueue.isEmpty()) {
            //只有到期的数据才会取出，不然就依然在阻塞队列里面
            LOG.info(String.valueOf(delayedQueue.take()));
        }

    }

    private static void producer(DelayQueue<Delayed> delayedQueue) {
        for (int i = 0; i < 10; i++) {
            //延时了2000毫秒，也就是两秒
            delayedQueue.put(new DelayedTask(i * 2000, "delayedQueue task " + i));
        }
    }

    private static class DelayedTask implements Delayed {

        private long delay;

        private long expire;

        private String msg;

        public DelayedTask(long i, String s) {
            this.delay = i;
            this.msg = s;
            this.expire = System.currentTimeMillis() + delay;
        }

        /**
         * 指定到期时间计算规则
         */
        @Override
        public long getDelay(TimeUnit unit) {
            //这里是毫秒
            return unit.convert(this.expire - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
        }

        @Override
        public String toString() {
            return "DelayedTask{" +
                    "delay=" + delay +
                    ", expire=" + expire +
                    ", msg='" + msg + '\'' +
                    '}';
        }
    }
}
